package cn.sky.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author sky
 * @date 2025年09月17日 11:05
 * @description
 * @since 1.0.0
 */
@Configuration
@EnableAsync
public class AsyncConfig{
    // 配置类
    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(10);
        // 最大线程数
        executor.setMaxPoolSize(20);
        // 任务队列大小
        executor.setQueueCapacity(100);
        // 线程池名称前缀
        executor.setThreadNamePrefix("custom-async-");
        // 允许线程的空闲时间
        executor.setKeepAliveSeconds(30);
        /**
         * 拒绝处理策略
         * CallerRunsPolicy()：交由调用方线程运行，比如 main 线程。
         * AbortPolicy()：直接抛出异常。
         * DiscardPolicy()：直接丢弃。
         * DiscardOldestPolicy()：丢弃队列中最老的任务。
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程初始化
        executor.initialize();
        return executor;
     }
    @Bean(name = "payAsyncExecutor")
    public Executor payAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(50);
        // 最大线程数
        executor.setMaxPoolSize(100);
        // 任务队列大小
        executor.setQueueCapacity(30);
        // 线程池名称前缀
        executor.setThreadNamePrefix("pay-async-");
        // 允许线程的空闲时间
        executor.setKeepAliveSeconds(30);
        /**
         * 拒绝处理策略
         * CallerRunsPolicy()：交由调用方线程运行，比如 main 线程。
         * AbortPolicy()：直接抛出异常。
         * DiscardPolicy()：直接丢弃。
         * DiscardOldestPolicy()：丢弃队列中最老的任务。
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程初始化
        executor.initialize();
        return executor;
    }
}
